/* Copyright 2007 Gearbox Software - http://www.gearboxsoft.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
     http:www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.*/

namespace GearBlog.Web.Controllers
{
	using System;
	using Castle.Components.Validator;
	using Castle.MonoRail.ActiveRecordSupport;
	using Castle.MonoRail.Framework;
	using GearBlog.Web.Filters;
	using GearBlog.Web.Models;
	using GearBlog.Web.Utils;

	/// <summary>
    /// Summary description for RegisterController
    /// </summary>
    [Layout("default")]
	[AuthenticationFilter(typeof(FormsAuthenticationAgent), RequiresLogin = false)]
    public class RegisterController:ExtendedControllerBase
    {
		public void Index()
		{
			CheckPublicRegistration();
			PropertyBag["UserInviteFormtype"] = typeof(UserInviteTicket);
		}
		public void SaveUserInvite([ARDataBind("UserInviteForm")] UserInviteTicket ticket)
		{
			CheckPublicRegistration();
			UserInviteTicket originalTicket = UserInviteTicket.FindByEmail(ticket.Email);
			bool isValid = true;
			if (originalTicket!=null )
			{
				originalTicket.SendInvitation(this);
				Flash["message"] =
					"You have registered before. Invitation email has been resent, please activate again according to instructions on email.";
			}
			else 
			{
				isValid = RedirectToReferrerOnError(ticket);
				if (isValid)
				{
					ticket.Save();
					ticket.SendInvitation(this);
					Flash["message"] =
						"Registration completed. Invitation email has been sent to the provided email, please activate according to instructions on email.";
				}
			}
			if (isValid) RedirectToReferrer();
		}

    	private void CheckPublicRegistration()
    	{
			Setting setting = Setting.FindFirst();
			if (!setting.AllowPublicRegistration) SecurityUtil.ShowAccessDenied(this);
    	}

    	public void ShowInviteActivate(Guid inviteKey)
        {
        	User currentUser = (User) Flash["UserForm"];
			if (currentUser==null)
			{
				UserInviteTicket inviteTicket = UserInviteTicket.FindByInviteKey(inviteKey);
				User user = new User();
				user.FullName = inviteTicket.FullName;
				user.Email = inviteTicket.Email;
				PropertyBag["UserForm"] = user;
			}
        
        }
        public void SaveUser([ARDataBind("UserForm")] User user)
        {
			if (RedirectToReferrerOnError(user))
			{
				user.SetPasswordHash();
				AssignDefaultRoles(user);
				user.Save();
				RedirectToAction("Thankyou");
			}
        }
		private void AssignDefaultRoles(User user)
		{
			Setting setting = Setting.FindFirst();
			foreach (Role role in setting.DefaultRoles)
			{
				user.Roles.Add(role);
			}

		}

    	public bool RedirectToReferrerOnError(User user)
		{
			return RedirectToReferrerOnError<User>(user, "UserForm");
		}
		private bool RedirectToReferrerOnError<T>(T arObject, string entityKey)
			where T:ExtendedActiveRecordBase<T>
		{
			ValidatorRunner runner;
			RunWhen runWhen = RunWhen.Everytime;
			if (arObject.Id == 0)
				runWhen = RunWhen.Everytime | RunWhen.Insert;

			if (!IsValid(arObject, out runner, runWhen))
			{
				Flash["ErrorSummary"] = runner.GetErrorSummary(arObject);
				Flash[entityKey] = arObject;
				RedirectToReferrer();
				return false;
			}
			else
				return true;
		}


    	public bool RedirectToReferrerOnError(UserInviteTicket ticket)
		{
    		return RedirectToReferrerOnError<UserInviteTicket>(ticket, "UserInviteForm");
		}
		public void Thankyou()
		{
			
		}
    }
}
